ASP.NET Web Form Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

ASP.NET Web Forms caching technique

Back to: ASP.NET Web Form Tutorial

In ASP.NET Web Forms, caching is a technique used to improve performance by storing the result of expensive operations (like database queries or complex calculations) so that subsequent requests can retrieve this data without having to recompute or re-fetch it. There are several ways to implement caching in ASP.NET Web Forms:

1. Output Caching

Output caching stores the generated HTML output of a page or user control to avoid regenerating it on every request.

How to use Output Caching:

  • You can apply output caching to the entire page or part of it using the OutputCache directive in the .aspx file.
aspx
< %@ OutputCache Duration="60" VaryByParam="none" %>
  • Duration specifies how long the page's output will be cached (in seconds).
  • VaryByParam allows caching based on query string parameters or form variables, so different variations of the page can be cached.

Example:

aspx
< %@ OutputCache Duration="300" VaryByParam="None" %>

This would cache the page for 5 minutes (300 seconds).

2. Data Caching

Data caching allows you to cache data at a more granular level, such as objects, collections, or database query results, so that they can be reused across requests without regenerating them.

How to use Data Caching:

  • You can use the Cache object in the Page_Load or any other method.

Example:

csharp
if (Cache["SomeData"] == null)
{
// Simulate expensive operation like database query
var data = GetDataFromDatabase();
Cache["SomeData"] = data;
}
else
{
var data = (YourDataType)Cache["SomeData"];
}
  • Sliding Expiration: This causes the cache to expire if it hasn't been accessed within a specified period.
csharp
Cache.Insert("SomeData", data, null, DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration);
  • Absolute Expiration: This specifies an exact time when the cached data will expire.
csharp
Cache.Insert("SomeData", data, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);

3. Application Caching

Application-wide caching stores data that can be shared across multiple sessions and users. You can store application data using the Application object.

Example:

csharp
Application["AppData"] = "Global data for all users";

4. Distributed Caching

In large-scale web applications, you may use distributed caching to share data across multiple servers (i.e., server farms). Redis, Memcached, or SQL Server can be used as distributed caching providers.

  • For Redis, you would install and configure the StackExchange.Redis library and then use the Redis server for caching.

Example with Redis:

IDatabase redisCache = connection.GetDatabase();
redisCache.StringSet("key", "value");
string value = redisCache.StringGet("key");

5. Output Caching for User Controls

You can cache user controls for a specific duration or based on parameters.

aspx
< %@ OutputCache Duration="60" VaryByParam="none" %>
< asp:SomeUserControl runat="server" id="MyControl" />

6. Caching in Master Pages

You can apply output caching to a master page, which will cache the output for all pages using that master page.

aspx
< %@ OutputCache Duration="60" VaryByParam="none" %>

Cache Dependency:

ASP.NET provides cache dependencies to automatically remove cached items when underlying data changes. You can use file-based cache dependencies, database dependencies, or other custom dependencies.

File-Based Cache Dependency:

string filePath = Server.MapPath("~/data.txt");
Cache.Insert("FileCache", data, new CacheDependency(filePath));

Database Dependency:

SqlCacheDependencyAdmin.EnableNotifications(connectionString);
SqlCacheDependencyAdmin.EnableTableForNotifications(connectionString, "tableName");

Best Practices:

  • Cache only what's necessary: Only cache data or output that is computationally expensive to regenerate.
  • Monitor Cache Size: Set proper eviction policies to prevent excessive memory usage.
  • Use Versioning: When caching dynamic content (e.g., pages with query parameters), ensure you cache multiple versions when necessary using VaryByParam.

Conclusion:

Caching in ASP.NET Web Forms significantly improves performance by reducing unnecessary data regeneration and page rendering. The best caching strategy depends on the application's needs, such as whether you're caching entire pages, partial views, or specific data objects.

Scroll to Top